package model.client;

import view.OnLineView;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class Client {

    public boolean connect_state = false;
    private Socket socket = null;
    private String account;
    private OnLineView onLineView = null;

    private ClientSendMsg clientSendMsg = null;
    private ClientListener clientListener = null;

    public Client(OnLineView onLineView) {

        this.onLineView = onLineView;
        this.account = String.valueOf(onLineView.getId());
        while (!connect_state) {
            connect();
            try {
                Thread.sleep(3*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void connect() {
        try {
            socket = new Socket("127.0.0.1", 55533);
            connect_state = true;
            ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());

            //发消息线程
            clientSendMsg = new ClientSendMsg(socket, out, account, this, onLineView);
            new Thread(clientSendMsg).start();
            //收消息线程
            clientListener = new ClientListener(socket, this, onLineView);
            new Thread(clientListener).start();
            //心跳包线程
            new Thread(new ClientHeart(socket, out, this)).start();
        } catch (IOException e) {
            e.printStackTrace();
            connect_state = false;
            try {
                socket.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    public void reconnect() {
        while (!connect_state) {
            System.out.println("正在尝试重新连接");
            connect();
            try {
                Thread.sleep(5*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public ClientSendMsg getClientSendMsg() {
        return clientSendMsg;
    }

    public void setClientSendMsg(ClientSendMsg clientSendMsg) {
        this.clientSendMsg = clientSendMsg;
    }

    public ClientListener getClientListener() {
        return clientListener;
    }

    public void setClientListener(ClientListener clientListener) {
        this.clientListener = clientListener;
    }

    public boolean isConnect_state() {
        return connect_state;
    }

    public void setConnect_state(boolean connect_state) {
        this.connect_state = connect_state;
    }
}
